import axios from 'axios';
import { Message } from 'element-ui';
import global_ from '../components/Global/index.vue';
// create an axios instance
const service = axios.create({
  baseURL: global_.BASE_URL,
  timeout: 50000000000
});
// 拦截器
service.interceptors.request.use(
  config => {
    // 在发送请求之前设置头部
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Token'] = token;
    }
    return config;
  },
  error => {
    // 输出错误信息
    // console.log(error) // for debug
    return Promise.reject(error);
  }
);
// 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code) {
      if (res.code === 10003) {
        Message({
          message: '登录过期，请重新登录',
          type: 'warning'
        });
        // 清除缓存
        localStorage.clear();
        setTimeout(() => {
          window.location.reload();
        }, 500);
      // eslint-disable-next-line no-empty
      } else {
      }
    } else {
      if (res.code === 10003) {
        Message({
          message: '登录过期，请重新登录',
          type: 'warning'
        });
        // 清除缓存
        localStorage.clear();
        setTimeout(() => {
          window.location.reload();
        }, 500);
      // eslint-disable-next-line no-empty
      } else {
      }
    }
    return res;
  },
  error => {
    // console.log('err' + error) // for debug
    Message({
      message: '暂无数据 ╮(╯▽╰)╭ ',
      type: 'warning',
      duration: 5 * 1000
    });
    // window.location.reload()
    return Promise.reject(error);
  }
);
export default service;
